#include <linux/fs.h>
#include <linux/module.h>
#include <linux/uaccess.h>

#define FILE_NAME "/tmp/testfile"

static struct file *file_ptr = NULL;

static int __init
fileop_init (void)
{
  // >>> 实现文件访问操作。
  loff_t pos = 0;
  char *buf;
  ssize_t ret;

  // 打开文件
  file_ptr = filp_open (FILE_NAME, O_RDWR | O_CREAT, 0666);//6表示0x111 即可读可写可执行
  if (IS_ERR (file_ptr))
    {
      printk (KERN_ALERT "Failed to open file\n");
      return PTR_ERR (file_ptr);
    }
  printk (KERN_INFO "File operation successful\n");

  // 写入文件
  pos = 0;
  ret = kernel_write (file_ptr, "so hard so painful!\n", 20, &pos);
  if (ret < 0)
    {
      printk (KERN_ALERT "Failed to write to file\n");
      filp_close (file_ptr, NULL);
      return ret;
    }

  // 分配缓冲区接收读到的内容
  buf = kmalloc (128, GFP_KERNEL);
  if (!buf)
    {
      printk (KERN_ALERT "Failed to allocate buffer\n");
      filp_close (file_ptr, NULL);
      return -ENOMEM;
    }

  // 读取文件
  pos = 0;
  ret = kernel_read (file_ptr, buf, 128, &pos);
  if (ret < 0)
    {
      printk (KERN_ALERT "Failed to read from file\n");
      kfree (buf);
      filp_close (file_ptr, NULL);
      return ret;
    }
  printk (KERN_INFO "%s\n", buf);

  // 释放缓冲区
  kfree (buf);

  return 0;
}

static void __exit
fileop_exit (void)
{
  if (file_ptr)
    {
      filp_close (file_ptr, NULL);
      printk (KERN_INFO "File closed\n");
    }
}

module_init (fileop_init);
module_exit (fileop_exit);

MODULE_LICENSE ("GPL");
MODULE_AUTHOR ("Your Name");
MODULE_DESCRIPTION ("Simple File Operation Module");
